package com.cai;

import java.io.*;
import java.util.*;

/**
 * @author：蔡松坡
 * @date：2020/11/26 08 : 16
 * @package：com.cai
 */
public class FileCvs {
    private static Properties properties = new Properties();
    private final static int SIZE = 100;
    private static int cpage=1;
    private static List<String> list = new ArrayList<>();
    private static int pageNum =0;  //总页数
    private static Moves moves = null;
    //="C:\\Users\\Administrator\\Desktop"+File.separator+"movies.csv"
    private static String path;
    private static InputStreamReader Reader = null;
    static{
        try{
            InputStream resourceAsStream = FileCvs.class.getClassLoader().getResourceAsStream("resources/file.properties");
            properties.load(resourceAsStream);
            path = properties.getProperty("path");
            Reader = new InputStreamReader(new FileInputStream(path));
            BufferedReader bfr = null;
            bfr = new BufferedReader(Reader);
            String str = null;
            bfr.readLine();
            while((str = bfr.readLine())!=null){
                list.add(str);
            }
            pageNum = list.size()%SIZE==0?(list.size()/SIZE):(list.size()/SIZE+1);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                Reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 查询所有
     * @return
     */
    public List<Moves> file(){
        int start =0;
        int end = (pageNum-1)*SIZE+(list.size()-(pageNum-1)*SIZE);
        return this.file(start,end);
    }

    /**
     * 分页查询
     * @param currentPage
     * @return  返回查询集合
     */
    public List<Moves> file(int currentPage){
        int start = (currentPage-1)*SIZE;
        int end = start+SIZE-1;
        if(currentPage==pageNum){
            end = start + (list.size()-(pageNum-1)*SIZE);
        }
        return this.file(start,end);
    }

    /**
     * 用于分页查询
     * @param start
     * @param end
     * @return
     */
    public List<Moves> file(int start,int end) {
        List<Moves> listMoves = new ArrayList<>();
        Moves moves = null;
//        System.out.println("start="+start+" list.size::"+list.size()+" end::"+end);
        for (int i=start;i<=end;i++){
            if(i==list.size()){break;}
            moves = new Moves();
            String s = list.get(i);
            String moveId = s.substring(0, s.indexOf(","));
            String title = s.substring(s.indexOf(",") + 1, s.lastIndexOf(","));
            String date = null;
            String gernes = null;
            String td = s.substring(s.indexOf(",")+1,s.lastIndexOf(","));
            if(td.lastIndexOf("(")!=-1&&td.lastIndexOf(")")!=-1){
                date = td.substring(td.lastIndexOf("(") + 1, td.lastIndexOf(")"));
            }
            gernes = s.substring(s.lastIndexOf(",") + 1);
            moves.setMoviesId(Integer.valueOf(moveId));
            moves.setTitle(title);
            moves.setDate(date);
            moves.setGernes(gernes);
            listMoves.add(moves);
        }

        return listMoves;
    }

    public void info(int currentPage){
        int start = (currentPage-1)*SIZE;
        int end = start+SIZE-1;
        if(currentPage==pageNum){
            end = start + (list.size()-(pageNum-1)*SIZE);
        }
        
        List<Moves> file = this.file(start,end);
        for (Moves moves1 : file) {
            System.out.print(moves1.getMoviesId()+"\t|\t");
            System.out.print(moves1.getTitle()+"\t|\t");
            System.out.print(moves1.getDate()+"\t|\t");
            System.out.println(moves1.getGernes());
            System.out.println("--------------------------------------------------------");
        }
        System.out.println("当前是第"+cpage+"页");
    }
    public void top(){
        System.out.println("==========================电影==========================");
        System.out.println("编号\t\t\t名称\t\t\t上映时间\t\t\t风格");
        System.out.println("=======================================================");
    }
    public void init(){
        System.out.println("1.查询  2.排序  3.统计  4.翻页  (输入其它数字退出系统)");
        Scanner scanner = new Scanner(System.in);
        int i = scanner.nextInt();
        switch(i){
            case 1:
                this.select();
                init();
                break;
            case 2:
                this.sort(1);
                cpage = 1;
                init();
                break;
            case 3:
                this.statistics();
                init();
                break;
            case 4:
                this.page();
                cpage = 1;
                init();
                break;
            default:
                System.exit(0);
                break;
        }
    }
    public void play(){
        //cpage = currentPage;
        this.top();
        this.info(cpage);
        this.init();
    }

    /**
     * 查询
     */
    public void select(){
        System.out.print("请输入电影名称关键字：");
        Scanner scanner = new Scanner(System.in);
        String mname = scanner.next();
        List<Moves> file = this.file();
//        System.out.println(file.size());
        int count = 0;
        this.top();
        for (Moves movies : file) {
            int i = movies.getTitle().toLowerCase().indexOf(mname.toLowerCase());
            if(i!=-1){
                count++;
                System.out.print(movies.getMoviesId()+"\t|\t");
                System.out.print(movies.getTitle()+"\t|\t");
                System.out.print(movies.getDate()+"\t|\t");
                System.out.println(movies.getGernes());
                System.out.println("--------------------------------------------------------");
            }
        }
        if(count==0){
            System.out.println("无法找到");
        }
    }
    /*****************************************/
    /**
     * 排序
     */
    public void sort(int currentPage){
        List<Moves> file = this.file(currentPage);
        TreeSet tree = new TreeSet();
        for (int i = 0; i < file.size(); i++) {
            Moves m = file.get(i);
            int index = i;
            String title = m.getTitle();
            for (int j = i+1; j < file.size(); j++) {
                Moves m2 = file.get(j);
                int i1 = m.compareTo(m2);
                tree.add(m2);
            }
        }
        this.top();
        Iterator iterator = tree.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
            System.out.println("--------------------------------------------------------");
        }
        this.sortF();

    }
    public void sortF(){
        System.out.println("<上一页**(第"+cpage+"页)**下一页> (任意其它退出当前)");
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();
        switch (next){
            case "<":
                if(cpage==1){
                    this.sort(1);
                    System.out.println("已经是第一页了");
                    break;
                }
                this.sort(--cpage);
                break;
            case ">":
                if(cpage==pageNum){
                    this.sort(pageNum);
                    System.out.println("已经是最后一页了");
                    break;
                }
                this.sort(++cpage);
                break;
            default:
                System.out.println("退出当前操作");
                break;
        }
    }
 /*****************************************************************/
    /**
     * 统计
     */
    public void statistics(){
        System.out.println("请选择排序方式（a.发行年份 b.风格）： (任意其它键退出当前)");
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();
        switch (next){
            case "a":
                this.statisticsA();
                this.statistics();
                break;
            case "b":
                this.statisticsB();
                this.statistics();
                break;
            default:
                this.init();
                break;
        }
    }
    public void statisticsA(){
        List<Moves> file = this.file();
        Map<String,Integer> map = new HashMap<>();
        int init=1;
        for (Moves moves1 : file) {
            if("".equals(moves1.getDate())||moves1.getDate()==null){
                continue;
            }
            if(map.containsKey(moves1.getDate())){
                Integer count = map.get(moves1.getDate());
                map.put(moves1.getDate(),++count);
            }else{
                map.put(moves1.getDate(),init);
            }
        }
        ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
        Collections.sort(entries,new Comparator<Map.Entry<String, Integer>>(){

            @Override
            public int compare(Map.Entry<String, Integer> v1, Map.Entry<String, Integer> v2) {
                return Integer.valueOf(v1.getKey()) - Integer.valueOf(v2.getKey());
            }
        });
        Iterator<Map.Entry<String, Integer>> iterator = entries.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, Integer> next = iterator.next();
            String key = next.getKey();
            Integer value = next.getValue();
            System.out.println("[ "+key+" ]年: 发行( "+value+" )部电影");
        }
    }
    public void statisticsB(){
        List<Moves> file = this.file();
        Map<String,Integer> map = new HashMap<>();
        int count=0;
        for (Moves moves1 : file) {
            String gernes = moves1.getGernes();
            if("(no genres listed)".equals(gernes)){
                continue;
            }
            String[] split = gernes.split("\\|");
            for (int j = 0; j < split.length; j++) {
                if(map.containsKey(split[j])){
                    Integer integer = map.get(split[j]);
                    map.put(split[j],++integer);
                }else{
                    map.put(split[j],++count);
                }
            }
        }
        Set<String> strings = map.keySet();
        for (String string : strings) {
            System.out.println("[ "+string+" ]风格: "+"( "+map.get(string)+" )部");
        }
    }
    /**
     * 翻页
     *
     */
    public void page(){
        System.out.println("<上一页****下一页>  (任意其它键退出)");
        Scanner scanner = new Scanner(System.in);
        String next = scanner.next();
        switch (next){
            case "<":
                if(cpage==1){
                    this.info(1);
                    System.out.println("已经是第一页了");
                    break;
                }
                this.info(--cpage);
                break;
            case ">":
                if(cpage==pageNum){
                    this.info(pageNum);
                    System.out.println("已经是最后一页了");
                    break;
                }
                this.info(++cpage);
                break;

            default:
                this.init();
                break;
        }
        this.page();
    }
    public static void main(String[] args) {
        FileCvs fileCvs = new FileCvs();
        fileCvs.play();
    }

}
